package util;

import com.alibaba.druid.pool.DruidDataSource;
import com.mysql.jdbc.AbandonedConnectionCleanupThread;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;

/**
 * @Author:
 * @Date: 2020-05-06
 * @Description: @PACKAGE:util
 * @version: 1.0
 */

@WebListener()
public class AppListener implements ServletContextListener {

    // Public constructor is required by servlet spec
    public AppListener() {
    }


    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {

    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        DruidDataSource druidDataSource= (DruidDataSource) DruidUtils.getDataSource();
        druidDataSource.close();
        System.out.println("关闭连接池");
        try {
            Enumeration<Driver> drivers = DriverManager.getDrivers();
            while(drivers.hasMoreElements()){
                DriverManager.deregisterDriver(drivers.nextElement());
                System.out.println("解除注册");
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            AbandonedConnectionCleanupThread.shutdown();
            System.out.println("关闭 Abandoned 线程");
        } catch (Exception e) {
            System.out.println("ContextFinalizer:SEVERE problem cleaning up: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
